/*
 * Copyright 2013 Rivaldo.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jety.commons.domain;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import org.jety.commons.exception.JsonRpcException;
import org.jety.commons.exception.JsonRpcRemoteException;
import org.jety.commons.typechecker.AbstractTypeChecker;
import org.jety.commons.typechecker.GsonTypeChecker;
import org.jety.commons.util.JsonRpcConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Rivaldo
 */
public class HandlerManager {

    private static final Logger LOG = LoggerFactory.getLogger(HandlerManager.class);

    private final Map<String, HandleEntry<?>> handlers;
    private volatile boolean locked = false;

    private final AbstractTypeChecker typeChecker;

    public HandlerManager() {
        this.handlers = new HashMap<String, HandleEntry<?>>();
        this.typeChecker = new GsonTypeChecker();
    }

    public <T> void addHandler(String name, T handler, Class<T>... classes) throws RuntimeException {

        if (locked) {
            throw new JsonRpcException("Executor has been locked, can't add more handlers");
        }

        synchronized (handlers) {
            HandleEntry<T> handleEntry = new HandleEntry<T>(typeChecker, handler, classes);
            if (this.handlers.containsKey(name)) {
                throw new IllegalArgumentException("Handler already exists");
            }
            this.handlers.put(name, handleEntry);
        }
    }

    public void addGenericHandler(String name, Object handler, Class<?>... classes) {

        if (locked) {
            throw new JsonRpcException("Executor has been locked, can't add more handlers");
        }

        synchronized (handlers) {
            HandleEntry handleEntry = new HandleEntry(typeChecker, handler, classes);
            if (this.handlers.containsKey(name)) {
                throw new IllegalArgumentException("Handler already exists");
            }
            this.handlers.put(name, handleEntry);
        }

    }

    public void lockHandlers() {
        if (!locked) {
            synchronized (handlers) {
                locked = true;
            }
            LOG.info("Locking executor to avoid modification.");
        }
    }

    public Method getHandlerMethod(JsonRpcMethod jsonMethod) throws JsonRpcRemoteException {

        HandleEntry<?> handleEntry = handlers.get(jsonMethod.getHandleName());

        if (handleEntry == null) {
            throw noHandlerException();
        }

        Method method = getExecutableMethod(jsonMethod, handleEntry);

        if (method == null) {
            throw noMethodException();
        }

        return method;
    }

    public Object getHandler(JsonRpcMethod jsonMethod) throws JsonRpcRemoteException {

        HandleEntry<?> handleEntry = handlers.get(jsonMethod.getHandleName());

        if (handleEntry == null) {
            throw noHandlerException();
        }

        return handleEntry.getHandler();
    }

    private Method getExecutableMethod(JsonRpcMethod jsonMethod, HandleEntry<?> handleEntry) {

        Method executableMethod = null;
        String methodName = jsonMethod.getMethodName();

        for (Method method : handleEntry.getMethods()) {

            if (method.getName().equals(methodName)) {
                if (jsonMethod.canExecute(method)) {
                    executableMethod = method;
                    break;
                }
            }
        }

        return executableMethod;
    }

    private JsonRpcRemoteException noHandlerException() {
        return new JsonRpcRemoteException(JsonRpcConstants.INVALID_PARAMS_ERROR_CODE, "No such handler exists");
    }

    private JsonRpcRemoteException noMethodException() {
        return new JsonRpcRemoteException(JsonRpcConstants.METHOD_NOT_FOUND_ERROR_CODE, "No such method exists");
    }
}
